<template>
  <div>
    <van-nav-bar title="X X 头条 - 登录"></van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          {
            required: true,
            message: '请填写手机号',
            trigger: 'onChange',
            pattern: /^1[3456789]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoding"
          :disabled="isLoding"
          loading-text="程序员拼命加载ing..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import Notify from '@/ui/Notify'
import { loginAPI } from '@/api'
import { setToken } from '@/utils/token'
import { setStorage } from '@/utils/storage'
export default {
  name: 'myLogin',
  data () {
    return {
      formLogin: {
        mobile: '13911111111',
        code: '246810' // 默认只能用246810后台规定了
      },
      isLoding: false // 加载状态
    }
  },
  methods: {
    // 登录按钮的点击事件
    async onSubmit () {
      this.isLoading = true
      try {
        const res = await loginAPI(this.formLogin)
        setToken(res.data.data.token)
        Notify({ type: 'success', message: '登录成功' })
        setStorage('refresh_token', res.data.data.refresh_token)

        this.$router.replace(this.$route.query.path || '/')
      } catch (err) {
        Notify({ type: 'warning', message: '手机号或密码错误' })
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
